package com.payease.ezt.dialog;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.webkit.WebHistoryItem;
import android.widget.AdapterView;
import android.widget.ListView;

import com.payease.ezt.R;
import com.payease.ezt.adapter.WebHistoryAdapter;
import com.payease.ezt.activity.AboutDetailActivity;
import com.payease.ezt.activity.MainActivity;

import java.util.List;

/**
 * Created by wuyong on 16/8/3.
 */
public class WebHistoryDialog extends DialogFragment implements AdapterView.OnItemClickListener {

    private ListView lvHistory;
    private WebHistoryAdapter adapter;
    private List<WebHistoryItem> webHistoryItems;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        // Get the layout inflater
        View view = View.inflate(getActivity(), R.layout.web_history, null);

        lvHistory = (ListView) view.findViewById(R.id.lv_history);
        adapter = new WebHistoryAdapter(webHistoryItems,getActivity());
        adapter.setWebItems(webHistoryItems);
        lvHistory.setAdapter(adapter);
        lvHistory.setOnItemClickListener(this);

        builder.setView(view);
        builder.setCancelable(true);
        return builder.create();
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    public void setWebHistoryItems(List<WebHistoryItem> webHistoryItems){
        this.webHistoryItems = webHistoryItems;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (getActivity() instanceof MainActivity){
            ((MainActivity)getActivity()).webEZT.loadUrl(webHistoryItems.get(position).getOriginalUrl());
        }else if(getActivity() instanceof AboutDetailActivity){
            ((AboutDetailActivity)getActivity()).webEZT.loadUrl(webHistoryItems.get(position).getOriginalUrl());
        }
        dismiss();
    }
}
